<script setup lang="ts">
import {computed, ref} from 'vue'

defineProps<{
  show: boolean
}>()

const floatingRef = ref<HTMLElement>()

const width = computed(() => {
  if (!floatingRef.value) return '0'
  console.log(floatingRef.value.offsetWidth)
  return floatingRef.value.offsetWidth + 'px'
})
</script>

<template>
  <div class="floating-container" ref="floatingRef">
    <slot/>
    <Transition name="fade">
      <div
          v-if="show"
          class="floating-content">
        <slot name="floating"/>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.floating-container {
  /* 关键：设置为相对定位，作为绝对定位的参考 */
  position: relative;
  /* 重要：设置为 inline-block 以适应内容宽度 */
  display: inline-block;
}

.floating-content {
  /* 关键：绝对定位不会影响其他元素布局 */
  position: absolute;
  z-index: 9999;

  /* 样式 */
  background: white;
  border-radius: 3px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  width: v-bind(width);

  transform-origin: left top;
}

/* 添加关键帧动画 */
@keyframes float-in {
  0% {
    opacity: 0;
    transform: scale(0);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes float-out {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0;
    transform: scale(0);
  }
}

/* Vue transition classes */
.fade-enter-active {
  animation: float-in 0.3s cubic-bezier(0.23, 1, 0.32, 1);
}

.fade-leave-active {
  animation: float-out 0.3s ease forwards;
}

</style>